package com.cj.webapp_Start.sp_network

import android.util.Base64
import android.util.Log
import com.google.gson.GsonBuilder
import com.cj.webapp_Start.sp_network.encryption.AESUtils
import com.cj.webapp_Start.sp_network.encryption.AESUtilsExt
import com.cj.webapp_Start.sp_network.encryption.RSAUtilsExt

class ParamsGenerator(var data: String) {
    var key: String? = null

    private fun getParamsKey(): String {
        if (key == null) {
            key = randomKey().substring(0, 16)
        }
        return key!!
    }

    private fun randomKey(): String {
        return AESUtils.getBase64Key()
    }

    fun buildRequestData(): String {
        var aesKey = getParamsKey()
        Log.i("buildRequestData", "key $aesKey")
        var aesData = AESUtilsExt.encryptToBase64(data, aesKey)
        var rsaKey = Base64.encodeToString(
            RSAUtilsExt.encryptByPublicKey(
                aesKey.toByteArray(),
                KeyMap.instance.getRsaPublicKey()
            ), Base64.NO_WRAP
        )
        Log.i("getRsaPublicKey", KeyMap.instance.getRsaPublicKey())
        Log.i("rsaKey", rsaKey)
        KeyMap.instance.putKey(rsaKey, aesKey)
        val result: Map<String, String> = HashMap<String, String>().apply {
            put("data", aesData)
            put("key", rsaKey)
        }

        val data = GsonBuilder().disableHtmlEscaping().create().toJson(result)
        Log.i("dara", data)
        return data
    }

    override fun toString(): String {
        return "ParamsGenerator(data='$data', key=$key)"
    }
}
